package com.google.ideas.MobileMeme.meme;

import java.util.List;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Loader;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

// An adapter that feeds Images to a ListView.
public class ImageStoreAdapter extends BaseAdapter {
    private static class ImageStoreLoader extends AsyncTaskLoader<List<BaseImage>> {
        public ImageStoreLoader(ImageStore store, Context context) {
            super(context);
            store_ = store;
            results_ = null;
            log("Created");
        }

        @Override
        public List<BaseImage> loadInBackground() {
            log("Starting Background Load");
        	results_ = store_.allImages(store_.getWritableDatabase()); 
            log("Finished Background Load with " + results_.size() + " items");
            return results_;
        }

        @Override protected void onStartLoading() {
            boolean printed = false;
            if (results_ != null) {
                log("onStartLoading: delivering results");
                deliverResult(results_);
                printed = true;
            }
            if (takeContentChanged() || results_ == null) {
                log("onStartLoading: forcing a load");
                forceLoad();
                printed = true;
            }
            if (!printed)
                log("onStartLoading: called but did nothing.");
        }

        @Override
		public void deliverResult(List<BaseImage> result) {
            log("deliverResult: started");
            if (result != results_) {
                log("deliverResult: different arg than results_");
            }
            if (isReset()) {
                log("deliverResult: reset.");
                results_ = null;
            }
            if (isStarted()) {
                log("deliverResult: started, delivering.");
                super.deliverResult(result);
            }
        }
        @Override protected void onStopLoading() {
            cancelLoad();
        }

        /* (non-Javadoc)
		 * @see android.content.Loader#onReset()
		 */
		@Override
		protected void onReset() {
			super.onReset();
			log("onReset()");
		}

		private void log(String s) { Log.d("image_store_loader", s); }

        private ImageStore store_;
        private List<BaseImage> results_;
    }

    public ImageStoreAdapter(ImageStore store, Context context) {
        store_ = store;
        images_ = null;
        context_ = context;
    }

    public Loader<List<BaseImage>> getLoader() {
    	Log.d("image_store_adapter", "getLoader() called");
        return new ImageStoreLoader(store_, context_);
    }

    public void setImages(List<BaseImage> images) {
        images_ = images;
        Log.d("image_store_adapter", "Got " + (images == null ? "null" : images.size()) + " images.");
        notifyDataSetChanged();
    }

    @Override public boolean areAllItemsEnabled() { return true; }
    @Override public int getItemViewType(int position) { return 1; }
    @Override public int getViewTypeCount() { return 1; }
    @Override public boolean hasStableIds() { return true; }
    @Override public boolean isEmpty() { return (images_ == null) || (images_.size() < 1); }
    @Override public boolean isEnabled(int position) { return true; }
    @Override public int getCount() { return (images_ == null)? 0 : images_.size(); }

    // Reverse the order, so new photos show up top.
    @Override public Object getItem(int position) { 
        return (images_ == null)? null : images_.get(position); 
    }
    @Override public long getItemId(int position) { 
        return (images_ == null)? -1 : images_.get(position).hashCode(); 
    }
    @Override public View getView(int position, View convertView, ViewGroup parent) {
        ImageView result = null;
        if (convertView != null && convertView instanceof ImageView) {
            result = (ImageView) convertView;
        } else {
            result = new ImageView(context_);
        //    parent.addView(result);
        }
        Bitmap img = images_.get(position).image();
        int height = img.getHeight();
        Log.d("image_store_adapter", "Returning a view for item " + position + ": " + images_.get(position) + " with height " + height);
        result.setImageBitmap(img);
        result.setMinimumHeight(height);
        return result;
    }
    
    private Context context_;
    private List<BaseImage> images_;
    private ImageStore store_;
}